﻿/**
* File: TpmapppermissionsService.cs
* Author: 汪杰
* Create Time:2021-11-18 9:04:53
* Email:15200358008@139.com
* 代码由TMCodeGenerator自动生成
**/
using AutoMapper;
using JSLCloud.App.Models.Tpmapppermissions;
using JSLCloud.Attributes;
using JSLCloud.DBModel;
using JSLCloud.Framework;
using JSLCloud.Models;
using JSLCloud.Utilities.SqlSugar;
using JSLCloud.Utilities.WebApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;


namespace JSLCloud.App.Mes.Service
{
    /// <summary>
    /// ITpmapppermissionsService 实现类
    /// </summary>
    [UseDI(ServiceLifetime.Scoped,typeof(ITpmapppermissionsService))]
    public class TpmapppermissionsService : ITpmapppermissionsService
    {
        private readonly IDbContext _db;//数据库操作实例对象
        private readonly ILogger<TpmapppermissionsService> _log;//日志操作实例对象
        private readonly IMapper _mapper;//AutoMapper实例
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public TpmapppermissionsService(IDbContext dbContext, ILogger<TpmapppermissionsService> logger,IMapper mapper)
        {
            _db = dbContext;
            _log = logger;
            _mapper = mapper;
        }
        
        /// <summary>
        /// 获取t_pm_app_permissions数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，查询操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<List<TpmapppermissionsQueryModel>>> GetAsync(RequestGet requestObject)
        {
            try
            {
                List<TpmapppermissionsQueryModel> queryData = null;//查询结果集对象
                RefAsync<int> totalNumber = -1;//总记录数
                var query = _db.Instance.Queryable<TpmapppermissionsDbModel>();
                //查询条件
                if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0)
                {
                    var conditionals = SqlSugarUtil.GetConditionalModels(requestObject.QueryConditions);
                    query.Where(conditionals);
                }
                //排序条件
                if(requestObject.OrderByConditions != null && requestObject.OrderByConditions.Count > 0)
                {
                    foreach (var item in requestObject.OrderByConditions)
                    {
                        var exp = SqlSugarUtil.GetOrderByLambda<TpmapppermissionsDbModel>(item.Column);
                        if (exp == null) continue;
                        if (item.Condition.ToLower() != "asc" 
                            && item.Condition.ToLower() != "desc") continue;
                        query.OrderBy($"{item.Column} {item.Condition}");
                    }
                }
                
                //执行查询
                if (requestObject.IsPaging)
                {
                    queryData = await query.Select(
						(t) => new TpmapppermissionsQueryModel 
						{
							ID = t.ID,
							Rid = t.Rid,
							Sckgbd = t.Sckgbd,
							Scwgbd = t.Scwgbd,
							Sctgbd = t.Sctgbd,
							Scycbd = t.Scycbd,
							Scjsjd = t.Scjsjd,
							Sccgjd = t.Sccgjd,
							Ckrkjl = t.Ckrkjl,
							Ckqtrk = t.Ckqtrk,
							Ckckjl = t.Ckckjl,
							Ckqtck = t.Ckqtck,
							Bb = t.Bb,
						})
                        .ToPageListAsync(requestObject.PageIndex, requestObject.PageSize, totalNumber);
                }
                else
                {
                    queryData = await query.Select(
						(t) => new TpmapppermissionsQueryModel 
						{
							ID = t.ID,
							Rid = t.Rid,
							Sckgbd = t.Sckgbd,
							Scwgbd = t.Scwgbd,
							Sctgbd = t.Sctgbd,
							Scycbd = t.Scycbd,
							Scjsjd = t.Scjsjd,
							Sccgjd = t.Sccgjd,
							Ckrkjl = t.Ckrkjl,
							Ckqtrk = t.Ckqtrk,
							Ckckjl = t.Ckckjl,
							Ckqtck = t.Ckqtck,
							Bb = t.Bb,
						})
                        .ToListAsync();
                }
                    
                //返回执行结果
                return ResponseUtil<List<TpmapppermissionsQueryModel>>.SuccessResult(queryData, totalNumber);
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return ResponseUtil<List<TpmapppermissionsQueryModel>>.FailResult(null, ex.Message);
            }
        }

        /// <summary>
        /// 根据角色ID查询权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public async Task<ResponseObject<TpmapppermissionsQueryModel>> GetByRoleIdAsync(int roleId)
        {
            try
            {
                var permission = await _db.Instance.Queryable<TpmapppermissionsDbModel>()
                    .Select(p=> new TpmapppermissionsQueryModel
                    {
                        ID = p.ID,
                        Rid = p.Rid,
                        Ckckjl = p.Ckckjl,
                        Ckqtck = p.Ckqtck,
                        Ckqtrk = p.Ckqtrk,
                        Ckrkjl = p.Ckrkjl,
                        Bb = p.Bb,
                        Sccgjd = p.Sccgjd,
                        Scjsjd = p.Scjsjd,
                        Sckgbd = p.Sckgbd,
                        Sctgbd  = p.Sctgbd,
                        Scwgbd = p.Scwgbd,
                        Scycbd = p.Scycbd                         
                    })
                    .Where(p => p.Rid == roleId)                    
                    .SingleAsync();
                if (permission == null)
                    permission = new TpmapppermissionsQueryModel();
                //返回执行结果
                return ResponseUtil<TpmapppermissionsQueryModel>.SuccessResult(permission);
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return ResponseUtil<TpmapppermissionsQueryModel>.FailResult(new TpmapppermissionsQueryModel(), ex.Message);
            }
        }

        /// <summary>
        /// 新增t_pm_app_permissions数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，新增操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> PostAsync(RequestPost<TpmapppermissionsAddModel> requestObject)
        {
            try
            {
                //如果没有新增数据，返回错误信息
                if (requestObject.PostData == null && requestObject.PostDataList == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                var result = false;
                //批量新增的优先级高于单条数据新增，且只会执行一个新增操作
                if(requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    var addList = _mapper.Map<List<TpmapppermissionsAddModel>, List<TpmapppermissionsDbModel>>(requestObject.PostDataList);
                    result = await _db.Instance.Insertable(addList).ExecuteCommandAsync() > 0;
                }
                else
                {
                    await _db.Instance.Deleteable<TpmapppermissionsDbModel>().Where(p => p.Rid == requestObject.PostData.Rid).ExecuteCommandAsync();
                    var addModel = _mapper.Map<TpmapppermissionsDbModel>(requestObject.PostData);
                    result = await _db.Instance.Insertable(addModel).ExecuteCommandAsync() > 0;
                }
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "新增数据失败!");
            }
            catch(Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
        /// <summary>
        /// 修改t_pm_app_permissions数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> PutAsync(RequestPut<TpmapppermissionsEditModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                //批量更新优先级高于单记录更新
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量更新
                    var editList = _mapper.Map<List<TpmapppermissionsEditModel>, List<TpmapppermissionsDbModel>>(requestObject.PostDataList);
                    result = await _db.Instance.Updateable(editList).ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录更新
                    var editModel = _mapper.Map<TpmapppermissionsDbModel>(requestObject.PostData);
                    result = await _db.Instance.Updateable(editModel).ExecuteCommandAsync() > 0;
                }
                
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "修改数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
        /// <summary>
        /// 删除t_pm_app_permissions数据
        /// </summary>
        /// <param name="requestObject"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> DeleteAsync(RequestDelete<DeleteModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有删除数据，返回错误信息
                if (requestObject.PostData == null && requestObject.PostDataList == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData、PostDataList不能都为null");
                //单记录删除
                result = await _db.Instance.Deleteable<TpmapppermissionsDbModel>()
                    .Where(p => p.Rid == requestObject.PostData.ID).ExecuteCommandAsync() > 0;

                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "删除数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
    }
}
